/* eslint indent: ["off"] */
/* eslint space-before-function-paren: ["off"] */
/* eslint no-async-promise-executor: ["off"] */

const _ = require('lodash')

// 100 条数据，32秒
const initGroupAccuracyMap = async (pool, groupArray, table_name, file_name) => {
  // const BATCH_SIZE = 1000; // 每次查询1000个分组，根据实际情况调整
  const BATCH_SIZE = 100 // 每次查询1000个分组，根据实际情况调整
  const result = {}
  const groupNames = groupArray.map((item) => item.group_name)

  try {
    const batches = _.chunk(groupNames, BATCH_SIZE)
    const batchPromises = batches.map(async (batch, index) => {
      const connection = await pool.getConnection()
      try {
        const query = `
          SELECT group_name, accuracy, time
          FROM ${table_name}
          WHERE group_name IN (${batch.map(() => '?').join(', ')})
          ORDER BY time ASC;
        `

        const [rows] = await connection.execute(query, batch)
        // console.log(`Rows fetched for batch ${index + 1}:`, rows.length)

        for (const row of rows) {
          const { group_name, accuracy } = row
          if (!result[group_name]) {
            result[group_name] = []
          }
          result[group_name].push(accuracy)
        }
      } finally {
        connection.release()
      }
    })

    await Promise.all(batchPromises)

    //
    return result
  } catch (error) {
    console.error('Error in initGroupAccuracyMap:', error)
    throw error // 重新抛出错误，让调用者知道发生了错误
  }
}
module.exports = { initGroupAccuracyMap }
